import { get, set } from '@/utils/auth';
import router, { asyncRoutes, constanRoutes } from '@/router';
import { getRouters } from '@/api/memu';
import Layout from '@/layout';

export const filterAysncRouter = routeList => {
  return routeList.filter(route => {
    if (route.component) {
      if (route.component === 'Layout' || route.component === 'LayoutPage') {
        route.component = Layout;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children && route.children.length) {
      filterAysncRouter(route.children);
    }
    return true;
  });
};

export const loadView = view => {
  if (process.env.NODE_ENV === 'development') {
    return resolve => require([`@/views/${view}`], resolve);
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`);
  }
};

const state = {
  route: [],
  hasGetRoute: get('RouteList') > 0,
  addRoute: [],
  menuNavRoute: [],
};
const mutations = {
  SET_ROUTE: (state, routes) => {
    state.addRoute = routes;
    state.route = constanRoutes.concat(routes);
  },
  SET_MENUNAV_ROUTE: (state, routes) => {
    state.menuNavRoute = routes;
  },
};
const actions = {
  async generateRoutes({ commit, state }) {
    return await getRouters().then(response => {
      const sdata = JSON.parse(JSON.stringify(response.data));
      const rdata = JSON.parse(JSON.stringify(response.data));
      const accessedRoutes = filterAysncRouter(sdata);
      const menunavRoutes = filterAysncRouter(rdata);
      commit('SET_ROUTE', accessedRoutes);
      commit('SET_MENUNAV_ROUTE', menunavRoutes);
      return Promise.resolve(accessedRoutes);
    });
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
